package at.ac.tuwien.dse.health.security;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

/**
 * @author Bernhard Nickel
 * @author Gregor Schauer
 * @author Dominik Strasser
 */
public class SecurityAspect {
	private static final Logger logger = LogManager.getLogger(SecurityAspect.class);

	public Object doSecuredOperation(ProceedingJoinPoint pjp) throws Throwable {
		Secured secured = ((MethodSignature) pjp.getSignature()).getMethod().getAnnotation(Secured.class);
		if (secured == null) {
			//this shouldn't happen
			logger.error("Missconfigured security aspect detected!");
			return pjp.proceed();
		}
		Object role=SecurityContext.getRole();
		if(role==null){
			//we don't have any role
			throw new SecurityException("Not authorized: no role defined in security context");
		} else if(secured.inherited()) {
			//okay, check role
			if(secured.value().isInstance(role)){
				return pjp.proceed();
			} else
				throw new SecurityException("Not authorized: Required role "+secured.value()+", provided: "+role.getClass(),secured.value(),role.getClass(),role);
		} else{
			//we have to have exactly the specified role
			if(secured.value().equals(role.getClass())){
				return pjp.proceed();
			} else
				throw new SecurityException("Not authorized: Required role "+secured.value()+" (exactly), provided: "+role.getClass(),secured.value(),role.getClass(),role);
		}
	}
}
